package com.fingard.dsp.bank.directbank;

import com.fingard.common.utils.json.JSONUtils;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;

import java.util.Map;

public class UnifinedOrderBase extends DirectBase {
    protected String[] getOpenid(String p_appId, String p_appSecret, String p_code) {
        String[] tmpMsg = new String[]{"", ""};

        String tmpUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        if (StringHelper.isNullOrEmpty(tmpUrl)) {
            tmpMsg[0] = "-1";
            tmpMsg[1] = "未设置“通过code换取网页授权access_token”的地址,请检查BankFront.xml相关配置!";
        } else {
            tmpUrl = tmpUrl + "?appid=" + p_appId + "&secret=" + p_appSecret + "&code=" + p_code
                    + "&grant_type=authorization_code";
            WriteBankLogStep2(tmpUrl);
            WebRequest tmpWebRequest = new WebRequest(tmpUrl);
            String[] tmpRet = tmpWebRequest.upload(null, "UTF-8");
            if (tmpRet[0].length() == 0) {
                WriteBankLogStep3(tmpRet[1]);
                if (tmpRet[1].startsWith("{")) {
                    Map<String, String> retHash = JSONUtils.json2Map(tmpRet[1]);
                    if (retHash != null) {
                        if (retHash.containsKey("openid")) {
                            tmpMsg[0] = "";
                            tmpMsg[1] = retHash.get("openid");
                        } else {
                            tmpMsg[0] = "-1";
                            String errcode = "";
                            if (retHash.containsKey("errcode")) {
                                errcode = retHash.get("errcode");
                            }
                            String errmsg = "";
                            if (retHash.containsKey("errmsg")) {
                                errmsg = retHash.get("errmsg");
                            }
                            tmpMsg[1] = StringHelper.joinNotEmpty("-", errcode, errmsg);
                        }
                    } else {
                        tmpMsg[0] = "-1";
                        tmpMsg[1] = "获取Openid微信返回为空";
                        WriteBankLogLn("获取Openid微信返回信息解析错误，原信息：" + tmpRet[1]);
                    }
                } else {
                    tmpMsg[0] = "-1";
                    tmpMsg[1] = tmpRet[1];
                }
            } else {
                tmpMsg[0] = "-1";
                tmpMsg[1] = tmpRet[1];
                WriteBankLogLn(tmpRet[0] + "\r\n" + tmpRet[1]);
            }
        }

        return tmpMsg;
    }
}